/**
* @file acl_rt_impl_base.cpp
*
* Copyright (c) Huawei Technologies Co., Ltd. 2025. All Rights reserved.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/

#include "acl_rt_impl_base.h"
#include <mutex>
#include <string>
#include <fstream>
#include <sstream>
#include "runtime/dev.h"
#include "runtime/acl_rt_impl.h"
#include "acl/acl_base.h"
#include "common/common_inner.h"
#include "common/log_inner.h"
#include "common/error_codes_inner.h"
#include "common/util/error_manager/error_manager.h"

namespace {
constexpr size_t DATA_MEMORY_ALIGN_SIZE = 32UL;
constexpr size_t SOC_VERSION_LEN = 128U;
std::mutex aclSocVersionMutex;
std::string aclSocVersion;
std::recursive_mutex aclInitMutex;
uint64_t aclInitRefCount = 0;
std::string aclConfigStr;
}

namespace acl {
aclError GetAlignedAndPaddingSize(const size_t size, const bool isPadding, size_t &alignedSize)
{
    // check overflow, the max value of size must be less than 0xFFFFFFFFFFFFFFFF-32*2
    if ((size + (DATA_MEMORY_ALIGN_SIZE * 2UL)) < size) {
        ACL_LOG_INNER_ERROR("[Check][Size]size too large: %zu", size);
        return ACL_ERROR_INVALID_PARAM;
    }

    // align size to multiple of 32 and padding 32 if needed
    const size_t appendSize = isPadding ? DATA_MEMORY_ALIGN_SIZE * 2UL : DATA_MEMORY_ALIGN_SIZE;
    alignedSize = (size + appendSize - 1UL) / DATA_MEMORY_ALIGN_SIZE * DATA_MEMORY_ALIGN_SIZE;
    return ACL_SUCCESS;
}

aclError InitSocVersion()
{
    const std::unique_lock<std::mutex> lk(aclSocVersionMutex);
    if (aclSocVersion.empty()) {
        // get socVersion
        char_t socVersion[SOC_VERSION_LEN] = {};
        const auto rtErr = rtGetSocVersion(socVersion, static_cast<uint32_t>(sizeof(socVersion)));
        if (rtErr != RT_ERROR_NONE) {
            ACL_LOG_INFO("can not get soc version, runtime errorCode is %d", static_cast<int32_t>(rtErr));
            return ACL_GET_ERRCODE_RTS(rtErr);
        }
        aclSocVersion = std::string(socVersion);
    }
    ACL_LOG_INFO("get SocVersion success, SocVersion = %s", aclSocVersion.c_str());
    return ACL_SUCCESS;
}

const std::string &GetSocVersion()
{
    ACL_LOG_INFO("socVersion is %s", aclSocVersion.c_str());
    return aclSocVersion;
}

bool GetAclInitFlag()
{
    return aclInitRefCount > 0UL;
}

uint64_t &GetAclInitRefCount()
{
    return aclInitRefCount;
}

std::recursive_mutex &GetAclInitMutex()
{
    return aclInitMutex;
}

std::string &GetConfigPathStr()
{
    return aclConfigStr;
}

void SetConfigPathStr(std::string &configStr)
{
    aclConfigStr = configStr;
}

aclError GetStrFromConfigPath(const char *configPath, std::string &configStr) {
    // 文件路径为空，按照空文件处理
    if (configPath != nullptr && strlen(configPath) != 0UL) {
        char_t realPath[MMPA_MAX_PATH] = {};
        if (mmRealPath(configPath, realPath, MMPA_MAX_PATH) != EN_OK) {
            ACL_LOG_ERROR("Invalid file: %s", configPath);
            return ACL_ERROR_INVALID_FILE;
        }
        std::ifstream file(realPath, std::ios::binary);
        if (!file.is_open()) {
            ACL_LOG_ERROR("Failed to open file: %s", configPath);
            return ACL_ERROR_INVALID_FILE;
        }

        std::stringstream buffer;
        buffer << file.rdbuf();
        configStr = buffer.str();
        file.close();  // 显式关闭文件
    }
    return ACL_SUCCESS;
}
} // namespace acl

const char *aclrtGetSocNameImpl()
{
    ACL_LOG_INFO("start to execute aclrtGetSocName.");
    // get socVersion
    const auto ret = acl::InitSocVersion();
    if (ret != ACL_SUCCESS) {
        ACL_LOG_INFO("can not init soc version, errorCode = %d", ret);
        return nullptr;
    }
    ACL_LOG_INFO("execute aclrtGetSocName successfully");
    return aclSocVersion.c_str();
}

aclError aclrtGetVersionImpl(int32_t *majorVersion, int32_t *minorVersion, int32_t *patchVersion)
{
    ACL_LOG_INFO("start to execute aclrtGetVersion.");
    ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(majorVersion);
    ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(minorVersion);
    ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(patchVersion);

    // Acl version is (*majorVersion).(*minorVersion).(*patchVersion)
    *majorVersion = ACL_MAJOR_VERSION;
    *minorVersion = ACL_MINOR_VERSION;
    *patchVersion = ACL_PATCH_VERSION;
    ACL_LOG_INFO("acl version is %d.%d.%d", *majorVersion, *minorVersion, *patchVersion);

    return ACL_SUCCESS;
}
